Skip to content

Conversation

Manfredss
Copy link

  • Add negative index detection and conversion in DealWithIndex function
  • Support negative indexing in advanced indexing like tensor[[-1]]
  • Fix issue75574: negative indexing in strided slice operations
  • Maintain backward compatibility with existing positive indexing
  • Add comprehensive test cases for negative indexing scenarios

Fixes: #issue75574

PR Category

Operator Mechanism

PR Types

Bug fixes

Description

修复PaddlePaddle中fancy indexing操作中负索引处理的问题。当使用tensor[[-1]]这种高级索引时,负索引没有被正确转换为正索引,导致索引错误。

复现步骤

import paddle

edge_index = paddle.arange(17758, dtype='int64')
strided_edge_index = edge_index[::32]
print(strided_edge_index[[-1]])  # 期望: 17728,实际可能出错
assert strided_edge_index[[-1]] == 17728  # 应该通过但实际失败

解决方案

paddle/fluid/pybind/slice_utils.hDealWithIndex函数中添加负索引处理逻辑:

// Handle negative indices for advanced indexing
if (indice.defined() && (indice.dtype() == paddle::DataType::INT64 || 
                        indice.dtype() == paddle::DataType::INT32)) {
  auto dims = transed_sub_tensor->dims();
  if (dims.size() > 0) {
    int64_t dim_size = dims[0];
    auto dim_size_tensor = full_ad_func({1}, dim_size, paddle::DataType::INT64, indice.place());
    
    auto negative_mask = less_than_ad_func(indice, zeros_like_ad_func(indice));
    auto positive_indices = where_ad_func(negative_mask, 
                                        add_ad_func(indice, dim_size_tensor), 
                                        indice);
    indice = positive_indices;
  }
}

修复内容

  • 修复tensor[[-1]]负索引问题
  • 支持步长切片后的负索引:strided_tensor[[-1]]
  • 支持混合索引:正索引和负索引混合使用
  • 向后兼容,不影响现有功能

测试用例

# 基本负索引
edge_index = paddle.arange(100, dtype='int64')
assert edge_index[[-1]].item() == 99

# 步长切片负索引
strided = edge_index[::10]
assert strided[[-1]].item() == 90

# 多负索引
result = edge_index[[-1, -2, -3]]
assert (result.numpy() == [99, 98, 97]).all()

影响范围

  • 仅影响fancy indexing中的负索引处理
  • 向后兼容,不影响现有正索引功能
  • 最小性能影响,只在检测到负索引时进行转换

Fixes: #issue75574

- Add negative index detection and conversion in DealWithIndex function
- Support negative indexing in advanced indexing like tensor[[-1]]
- Fix issue75574: negative indexing in strided slice operations
- Maintain backward compatibility with existing positive indexing
- Add comprehensive test cases for negative indexing scenarios

Fixes: #issue75574
Copy link

paddle-bot bot commented Oct 4, 2025

你的PR提交成功,感谢你对开源项目的贡献!
请关注后续CI自动化测试结果,详情请参考Paddle-CI手册
Your PR has been submitted. Thanks for your contribution!
Please wait for the result of CI firstly. See Paddle CI Manual for details.

@paddle-bot paddle-bot bot added the contributor External developers label Oct 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
contributor External developers
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant